//
//  StoreDetailsViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/4/28.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import Alamofire
import CoreLocation

class StoreDetailsViewController: BaseViewController {

    @IBOutlet var storeDetailsTableview: UITableView!
     var footerView: StoreDetailsFooterView?
     var showImageIndex : Int?
     var chooseImageType : Int? //0 封面图片 1 展示图片
    
     var storeModel :StoreModel?
     var storeTypeModels:[StoreTypeModel]?
     var tagRunnerImageUrl = ""
     var storeTypeId  = ""
     var isInstallId = ""
     var lonStr = ""
     var latStr = ""
    
    var provinceIdStr = ""
    var cityIdStr = ""
    var townIdStr = ""
    
    var provinceNameStr = ""
    var cityNameStr = ""
    var townNameStr = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        requestGetStoreDetails()
        requestGetStoreType()
        configView()
        baseSetNavRightButtonWithTitle("保存")
    }
    
    override func baseNavRightButtonPressed(_ button: UIButton) {
        print("保存")
        
        var Ids = [String]()
        for (photo) in (self.footerView?.imageArray)! {
            Ids.append(photo.id)
        }
        let photoStr = Ids.joined(separator:",")
        requestSaveStoreInfo(storeName:(footerView?.storeNameTF.text!)!, storeImageUrl:self.tagRunnerImageUrl, storeAddress:(footerView?.storeDetailsAddressTF.text!)!, phone:(footerView?.phoneTF.text!)!, isInstall: self.isInstallId, description:(footerView?.introductionTF.text!)!, content: (footerView?.detailsTF.text!)!, photos:photoStr)
    }
    
    func configView() -> Void {
        storeDetailsTableview.delegate = self
        storeDetailsTableview.dataSource = self
        storeDetailsTableview.separatorStyle = .none
        storeDetailsTableview.showsVerticalScrollIndicator = false
        footerView = StoreDetailsFooterView.getStoreDetailsFooterView()
        footerView?.storeDetailsAddressTF.delegate = self
        footerView?.tagRunnerBtn.addTarget(self, action: #selector(tagRunerEvents), for: .touchUpInside)
        footerView?.storeTypeBtn.addTarget(self, action: #selector(storeTypeBtnEvents), for: .touchUpInside)
        footerView?.chooseStoreAddressBtn.addTarget(self, action: #selector(storeAddressBtnEvents), for: .touchUpInside)
        footerView?.chooseLocationBtn.addTarget(self, action: #selector(chooseLocationBtnEvents), for: .touchUpInside)
        footerView?.isInstallPointBtn.addTarget(self, action: #selector(isInstallPointBtnEvents), for: .touchUpInside)
        footerView?.isInstallPointBtn.isEnabled = false
        footerView?.storeTypeBtn.isEnabled = false
        footerView?.callBackBlock({ (index) in
            print(index)
            self.showImageIndex = index
            self.chooseImageType = 1
            self.alertChooseTakePhotoOrAlbum(typeName: "展示图片")
        })
        footerView?.collectionviewHeight.constant = ScaleHeight(200);
        storeDetailsTableview.tableFooterView = footerView
    }
    
    @objc func tagRunerEvents() -> Void {//上传封面图片
        self.chooseImageType = 0
        alertChooseTakePhotoOrAlbum(typeName: "店铺封面图片")
    }
    
    @objc func storeTypeBtnEvents() -> Void {//门店类型
        var Ids = [String]()
        var titles = [String]()
        for (storeType) in storeTypeModels! {
            
            titles.append(storeType.title)
            Ids.append(storeType.id)
        }
        BRStringPickerView.showStringPicker(withTitle: "门店类型", dataSource: titles, defaultSelValue: titles[0], isAutoSelect: true) { (str,index) in
            
            self.storeTypeId = Ids[index]
            self.footerView?.storeTypeBtn.setTitle(str as? String, for: .normal)
        }
    }
    
    @objc func storeAddressBtnEvents() -> Void {//选择门店地址
        //解析数据
        let path = Bundle.main.path(forResource: "ldlcitylist", ofType: "plist")
        let dic = NSDictionary(contentsOfFile: path!)
        let baseCitymodel = CityDataModel.deserialize(from:dic)!
        let provinces = baseCitymodel.citylist
        var citys = [AddressModel]()
        var towns = [AddressModel]()
//        for provinceModel in provinces! {
//            for son in provinceModel.son! {
//                citys.append(son)
//            }
//        }
//        for cityModel in citys {
//            for son in cityModel.son! {
//             towns.append(son)
//            }
//        }
        let pmodel = provinces![0]
        citys = pmodel.son!
        let cmodel = citys[0]
        towns = cmodel.son!
        //弹出框
        let popPickerView = PopPickerView.getPopPickerView()
        popPickerView.provinces = provinces!
        popPickerView.citys = citys
        popPickerView.towns = towns
        popPickerView.callBackBlock { (pId,cId,tId)  in
            if pId == "cancle" || cId == "cancle" || tId == "cancle" {
            }else {
                
                    self.provinceIdStr = pId
                    self.cityIdStr = cId
                    self.townIdStr = tId
            }
            bgWindow?.hidBackgroundWindow()
        }
        popPickerView.callNameBackBlock { (provinceName,cityName,townName) in
            
            self.provinceNameStr = provinceName
            self.cityNameStr = cityName
            self.townNameStr = townName
        self.footerView?.chooseStoreAddressBtn.setTitle(self.provinceNameStr + self.cityNameStr + self.townNameStr, for: .normal)
            bgWindow?.hidBackgroundWindow()
        }
        bgWindow = DSHCBcakgroundWindow.setupBackgroundWindowAndShow()
        bgWindow?.shake(toShow: popPickerView)
        
    }
    
    @objc func isInstallPointBtnEvents() -> Void {//是否为安装点
        BRStringPickerView.showStringPicker(withTitle: "是否为安装点", dataSource: ["是","否"], defaultSelValue: "是", isAutoSelect: true) { (str,index) in
           
           self.isInstallId = "\(index + 1)"
       self.footerView?.isInstallPointBtn.setTitle(str as? String, for: .normal)
        }
    }
    
    @objc func chooseLocationBtnEvents() -> Void {//选择店铺定位地址
        let chooseLocationVC = ChooseLocationViewController()
        chooseLocationVC.chooseLoction = self; self.navigationController?.pushViewController(chooseLocationVC, animated: true)
    }

    //选择照片或者拍照
    func alertChooseTakePhotoOrAlbum(typeName:String) -> Void {
    let alertController = UIAlertController(title: "上传图片", message: typeName,
    preferredStyle: .actionSheet)
    let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
    let takephtotAction = UIAlertAction(title: "拍照", style: .default, handler:{
    action in
    let imagePicker = LDImagePicker.sharedInstance()
    imagePicker?.delegate = self as LDImagePickerDelegate
    imagePicker?.show(with: ImagePickerCamera, in: self, scale: 1)
    })
    let albumAction = UIAlertAction(title: "相册", style: .default, handler:{
    action in
    let imagePicker = LDImagePicker.sharedInstance()
    imagePicker?.delegate = self as LDImagePickerDelegate
    imagePicker?.show(with: ImagePickerPhoto, in: self, scale: 1)
    
    })
    alertController.addAction(cancelAction)
    alertController.addAction(takephtotAction)
    alertController.addAction(albumAction)
    self.present(alertController, animated: true, completion: nil)
    }
    
    //更新footerView
    func updateFooterView() -> Void {
        if ((storeModel) != nil) {
   
        //赋值
        tagRunnerImageUrl = (storeModel?.thumb)!
        isInstallId = (storeModel?.hide)!
        provinceIdStr = (storeModel?.provinceid)!
        cityIdStr = (storeModel?.cityid)!
        townIdStr = (storeModel?.areaid)!
        provinceNameStr = (storeModel?.province)!
        cityNameStr = (storeModel?.city)!
        townNameStr = (storeModel?.area)!
        latStr = (storeModel?.lat)!
        lonStr = (storeModel?.lng)!
            
        //更新UI
    footerView?.TagRunnerImageView.sd_setImage(with: NSURL(string:(storeModel?.thumb)!)! as URL, placeholderImage: UIImage.init(named: "addImage"))
        
        footerView?.introductionTF.text = storeModel?.content
        footerView?.detailsTF.text = storeModel?.description
        footerView?.storeNameTF.text = storeModel?.name
    footerView?.chooseStoreAddressBtn.setTitle(provinceNameStr + cityNameStr + townNameStr, for: .normal)
    footerView?.storeTypeBtn.setTitle(storeModel?.jointitle, for: .normal)
            footerView?.storeDetailsAddressTF.text = storeModel?.address
            footerView?.phoneTF.text = storeModel?.phone
        footerView?.imageArray = (storeModel?.acces)!
       
            if (footerView?.imageArray.count)! > 3 {
                footerView?.collectionviewHeight.constant = ScaleHeight(200);
            };
            footerView?.addImageCollectionview.reloadData()
        }
    }
    
    //根据地名获取经纬度
//    func getLonAndLat(address:String) -> Void {
//       let geoCoder = CLGeocoder()
//        geoCoder.geocodeAddressString(address) { (pls: [CLPlacemark]?, error: Error?)  in
//            if error == nil {
//                print("地理编码成功")
//                guard let plsResult = pls else {return}
//                let firstPL = plsResult.first
//                self.storeModel?.address = (firstPL?.name)!
//                self.latStr = "\((firstPL?.location?.coordinate.latitude)!)"
//                self.lonStr = "\((firstPL?.location?.coordinate.longitude)!)"
//            }else {
//                print("错误")
//            }
//        }
//    }
    
    
    //网络请求
    //获取店铺详情
    func requestGetStoreDetails() -> Void {
        Alamofire.request(getStoreDetailsUrl, method:.post, parameters:["sid":UserModel.shareUser.data?.storeId ?? String()])
            .responseString { response in

                switch response.result.isSuccess {
                case true:

                    var basemodel = BaseResponseOfModel<StoreModel>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!

                    switch basemodel.status! {
                    case true:
                        self.storeModel = basemodel.data
                        self.updateFooterView()
                    self.storeDetailsTableview.reloadData()
                        print("获取成功")
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }

                case false:
                    print(response.result.error!)
                }

        }
    }
    
    
    
    //上传单张封面图片
    func requestUploadCoverPhoto(imageName:String,imageData:Data) -> Void {
        //imageType 0 封面图片 1 展示图片....
        Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imageData, withName: "Filedata", fileName:imageName, mimeType: "image/jpeg")
        }, to: uploadPhotoUrl) { (encodingResult) in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseString { response in
                    
    switch response.result.isSuccess {
                case true:
                    var basemodel = BaseResponseOfModel<PhotoModel>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                    switch basemodel.status! {
                    case true:
                        self.tagRunnerImageUrl = (basemodel.data?.thumb)!
                        print("上传成功")
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
        }
                case false:
                    print(response.result.error!)
                }
            }
            case .failure(let encodingError):
                print(encodingError)
            }
        }
    }
    
    //上传多张展示图片
    func requestUploadCoverPhotos(imageName:String,imageData:Data) -> Void {
//        0 1 2 3 4  展示图片....
        Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imageData, withName: "Filedata", fileName:imageName, mimeType: "image/jpeg")
        }, to: uploadPhotosUrl) { (encodingResult) in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseString { response in
                    
                    switch response.result.isSuccess {
                    case true:
                        var basemodel = BaseResponseOfModel<PhotoModel>()
                        basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                        switch basemodel.status! {
                        case true:
                    if (self.footerView?.imageArray.count)! > 0 {
                    if(self.footerView?.imageArray.count)! == self.showImageIndex! {
                            print("点击的最后一个")
                    if self.footerView?.imageArray.count != 5{//添加
                        self.addImageArrayEvents(model: basemodel.data!)
                        }else {//由于是最后一个 替换
                        self.replaceImageArrayEvents(model: basemodel.data!)
                              }
                        }else {//替换
                            print("其他的")
                        self.replaceImageArrayEvents(model: basemodel.data!)
                        }
                    } else {//第一个+
                    //添加到图片数组里面
                        self.addImageArrayEvents(model:basemodel.data!)

                      }
                            print("上传成功")
                        case false:
                             MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                        }
                    case false:
                        print(response.result.error!)
                    }
                }
            case .failure(let encodingError):
                print(encodingError)
            }
        }
    }
    
    //处理图片数组
    //替换
    func replaceImageArrayEvents(model:PhotoModel) -> Void {
        let photomodel = self.footerView?.imageArray[self.showImageIndex!]
        photomodel?.id = model.id
        photomodel?.url = HeadUrl + model.thumb
        self.footerView?.addImageCollectionview.reloadData()
    }
    //增加
    func addImageArrayEvents(model:PhotoModel) -> Void {
        model.url = HeadUrl + model.thumb
        self.footerView?.imageArray.append(model)
        self.footerView?.addImageCollectionview.reloadData()
    }
    
    //保存店铺信息
    func requestSaveStoreInfo(storeName:String,storeImageUrl:String,storeAddress:String,phone:String,isInstall:String,description:String,content:String,photos:String) -> Void {
        let param =
            ["name":storeName,
             "thumb":storeImageUrl,
             "address":storeAddress,
             "phone":phone,
             "description":description,
             "content":content,
             "hide":isInstall,
             "sid":UserModel.shareUser.data?.storeId ?? String(),
             "lat":self.latStr,
             "lng":self.lonStr,
             "province":provinceIdStr,
             "city":cityIdStr,
             "area":townIdStr,
             "acceids":photos,
             ] as [String : Any]
        
        Alamofire.request(editStoreDetailsUrl, method:.post, parameters:param)
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
                        hud?.mode = MBProgressHUDMode.text
                        hud?.labelText = "保存成功"
                        hud?.show(animated: true, whileExecuting: {                        Thread.sleep(forTimeInterval: 0.8)
                        }, completionBlock: {                    self.navigationController?.popViewController(animated: true)
                        })
                    case false:
                    MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    //获取店铺类型
    func requestGetStoreType() -> Void {
        
        Alamofire.request(getStoreTypeUrl, method:.post, parameters:nil)
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    var basemodel = BaseResponseOfArrayModel<StoreTypeModel>()
                    basemodel = BaseResponseOfArrayModel.deserialize(from: response.value)!
                    switch basemodel.status! {
                    case true:
                        self.storeTypeModels = basemodel.data
                        print("数据请求成功")
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension StoreDetailsViewController: UITableViewDelegate,UITableViewDataSource,LDImagePickerDelegate,UITextFieldDelegate,ChooseLocationDelegate {
    
    func postValueToVc(address: String, lon: String, lat: String) {
        self.latStr = lat
        self.lonStr = lon
    self.footerView?.chooseLocationBtn.setTitle(address, for: UIControlState.normal)
    }
    
    
//    func textFieldDidEndEditing(_ textField: UITextField) {
////        getLonAndLat(address: (textField.text!))
//        getLonAndLat(address:self.provinceNameStr+self.cityNameStr+self.townNameStr + (textField.text!))
//
//    }
    
    func imagePickerDidCancel(_ imagePicker: LDImagePicker!) {
        
    }
    
    func imagePicker(_ imagePicker: LDImagePicker!, didFinished editedImage: UIImage!) {
        let imageData = UIImageJPEGRepresentation(editedImage, 0.00001)
        let formatter = DateFormatter.init()
        formatter.dateFormat = "yyyyMMddHHmmss"
        let str = formatter.string(from:NSDate() as Date) + ".jpg"
        footerView?.TagRunnerImageView.image = editedImage
        if chooseImageType == 0 {
             requestUploadCoverPhoto(imageName: str, imageData: imageData!)
        }else {
             requestUploadCoverPhotos(imageName: str, imageData: imageData!)
        }
       
        
        
    }
    
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "storeDetailsCell", for: indexPath) as! StoreDetailsTableViewCell
        cell.selectionStyle = .none
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return ScaleHeight(40)
    }
    
//    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
////      footerView?.TagRunnerImageView.sd_setImage(with: NSURL(string:imageStr)! as URL, placeholderImage: UIImage.init(named: "addImage"))
//
//        return self.footerView
//    }
//
//    func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat {
//        return 1000
//    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 0.0001
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.0001
    }
    
    
    
}


